<template>
<!--  <p v-html="state.debug"></p>-->
<!--  <p v-html="state.debug2"></p>-->
<!--  <p v-html="state.debug3"></p>-->
<!--  <p v-html="state.debug4"></p>-->
<!--  <p v-html="state.debug5"></p>-->
<!--  <p v-html="state.debug6"></p>-->
	<div class="home">
		<header class="header">
			<div class="city" @click="state.areaShow = true">
				<van-icon color="#555555" name="location" size="14" />
				<span style="font-size: 13px">{{ state.pageInfo.city || '全部' }}</span>
				<van-icon class="play" color="#a5a5a5" name="play" size="12" />
			</div>
			<div class="tabs">
				<van-tabs
            swipeable
					v-model:active="state.active"
					line-width="30px"
					title-inactive-color="#A6A6A6"
					title-active-color="#333333"
					:before-change="tabsBeforeChange"
				>
					<van-tab v-for="item of state.tabs" :name="item" :title="item" >
            <swiperTab ref="swiperTabRef"></swiperTab>
          </van-tab>
				</van-tabs>
			</div>
			<div>
				<van-dropdown-menu active-color="#f54386">
					<van-dropdown-item
						title="性别筛选"
						v-model="state.pageInfo.sex"
						:options="state.sexOption"
						@change="sexMenuChange"
					/>
				</van-dropdown-menu>
			</div>
		</header>

		<main class="my_swiper_box">
			<swiper
				class="my_swiper"
				direction="vertical"
				:spaceBetween="15"
				:modules="[Virtual]"
				virtual
				@slideChange="onSlideChange"
			>
				<template v-for="(item, index) of state.menberList" :key="item.id">
					<swiper-slide class="swipe_item">
						<!-- 视频 -->
						<MyVideoPlay
							v-if="item.is_vip_video && item.vcr.video_url"
							:ref="(el) => setItemRef(el, item.id)"
							:item="item"
							@videoClick="videoClick(item.user_id)"
						/>
						<!-- 图片 -->
						<img class="img" v-else v-lazy="imgUrl + item.user_img" />

						<!-- 用户信息 -->
						<div class="user_info">
							<div>
								<span>{{ item.username }}</span>
								<img v-if="showVip(item)" class="vip" src="@/assets/img/vip_icon.png" />
								<img v-if="item.is_vip_video" class="certification" src="@/assets/img/certification_icon.png" />
							</div>
							<p class="info">{{ item.age }}岁 {{ item.height }}cm {{ item.job }} {{ item.income }}</p>
							<p>{{ item.province }} {{ item.city }}</p>
						</div>
						<!-- 头像 -->
						<van-image
							class="avatar"
							round
							width="40px"
							height="40px"
							fit="cover"
							:src="item.head_img_url"
							@click="avatarClick(item.user_id)"
						/>

						<!-- 收藏 -->
						<div class="share collection" v-debounce="() => collect(item.user_id, index)">
							<img v-if="item.is_collect" src="@/assets/img/collectionActive_icon.png" />
							<img v-else src="@/assets/img/collection_icon.png" />
							<span>{{ item.like_num }}</span>
						</div>
						<!-- 分享 -->
						<div class="share" @click="state.codeDialogShow = true">
							<img src="@/assets/img/share_icon.png" />
							<span>{{ item.share_num }}</span>
						</div>
						<!-- 电话 -->
						<a class="tel" :href="state.mobile" v-debounce="() => callMobile(item.mobile)">
							<img src="@/assets/img/tel_icon.png" />
						</a>
            <span class="tel_bottom_text">牵线</span>
					</swiper-slide>
				</template>
			</swiper>
		</main>

		<MyTabbar />

		<!-- 开通套餐会员弹窗 -->
		<vipPopup ref="vipPopupRef" @openVipPackage="openVipPackage" />

		<!-- 一元付费弹窗 -->
		<MyDialogBtn v-model:show="state.payShow" column>
			<template #content>
				<div>观看本视频需付费一元 观看，或成为平台VIP用户即可 享受全部免费观看！</div>
			</template>
			<template #btn>
				<van-button type="primary" @click="payOneYuan">付费一元</van-button>
				<van-button type="success" @click="becomeVip">成为VIP</van-button>
				<van-button type="success" @click="state.payShow = false">取消</van-button>
			</template>
		</MyDialogBtn>

		<!-- 认证会员弹窗 -->
		<MyDialogBtn v-model:show="state.vipShow">
			<template #content>
				<div>是否成为认证会员？</div>
			</template>
			<template #btn>
				<van-button type="primary" @click="router.push({ name: 'verifiedMember' })">去了解</van-button>
				<van-button type="success" @click="state.vipShow = false">再看看</van-button>
			</template>
		</MyDialogBtn>

    <!-- 分享说明 -->
    <MyDialogBtn v-model:show="state.codeDialogShow" column>
      <template #content>
        <div style="max-height: 50vh; overflow: scroll">
          <div style="margin-bottom: 30px">分享说明</div>
          <p v-html="state.promote_contents" style="font-size: 13px; text-align: left; line-height: 24px"></p>
        </div>
      </template>
      <template #btn>
        <van-button type="primary" @click="state.codeDialogShow = false">确定</van-button>
      </template>
    </MyDialogBtn>

		<van-popup v-model:show="state.areaShow" round position="bottom">
			<van-area :area-list="areaList" :value="state.areaDefaultCode" columns-num="2" @confirm="areaConfirm" @cancel="state.areaShow = false" />
		</van-popup>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick, onActivated } from 'vue';
import type { ComponentPublicInstance } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import type { NavigationFailure } from 'vue-router';
import { Virtual } from 'swiper';
import { Swiper, SwiperSlide } from 'swiper/vue';
import type { Swiper as SwiperClass } from 'swiper/types';
import { opendIdByCode, addUser, getAddressByGPS, memberInfo, wxPay, wxVipPay, bindUserRelate } from '@/api/common';
import {
	memberList,
	saveCollect,
	checkUserStateByOneYuan,
	createOneYuanOrder,
	createVipOrder,
	saveBrowseRecord,
	updateShareCount
} from '@/api/index';
import { getQueryString } from '@/utils/util';

import { useMainStore } from '@/store';
import useAuthorize from '@/hooks/authorize';
import wxApiReady from '@/hooks/wxApiReady';
import showVip from '@/hooks/showVip';
import MyTabbar from '@/components/MyTabbar.vue';
import MyVideoPlay from '@/components/MyVideoPlay.vue';
import MyDialogBtn from '@/components/MyDialogBtn.vue';
import vipPopup from './components/vipPopup.vue';
import swiperTab from './components/swiperTab.vue';
import type { AreaColumnOption, DropdownItemOption, ToastOptions } from 'vant';
import { Toast } from 'vant';
import { areaList } from '@vant/area-data';
import wx from 'weixin-jsapi';

const imgUrl = import.meta.env.VITE_IMG_URL;
const mainStore = useMainStore();
const router = useRouter();
const route = useRoute();
const state = reactive<any>({
  debug:'',
  debug2:'',
  debug3:'',
  debug4:'',
  debug5:'',
  debug6:'',
	showFlag: true,
	areaShow: false,
	areaDefaultCode: '110101',
  codeDialogShow: false,
  promote_contents:'点击右上角【...】分享到朋友圈或微信群：<br/>' +
      '①可成为注册会员推荐人；<br/>' +
      '②获得视频付费观看50%收益。',
	mobile: '#',
	pageInfo: {
		pageIndex: 1,
		pageSize: 10,
		user_id: mainStore.user_id,
		city: null,
		is_vip_video: null,
		share_user_id: route.query.share_user_id || '',
		state: 1,
		sex: ''
	},
	sexOption: [
		{ text: '查看全部', value: '' },
		{ text: '只看男性', value: '男' },
		{ text: '只看女性', value: '女' }
	],
	payShow: false,
	vipShow: false,
	active: 0,
	tabs: ['全部', '同城', '认证会员'],
	currentIndex: 0,

	menberList: [] as any[],

	province: '',
	city: '',
	country: ''
});

onMounted(async () => {
	if (route.query.parent_id) {
		// 保存推广码分享id
		mainStore.parent_id = (route.query.parent_id as string) || null;
	}

	if (mainStore.userInfo == null) {
		return getUserInfo();
	}

	bindMatchmakerRelate();
});

onActivated(async () => {
	if (!mainStore.isUserDetailPath) {
		state.pageInfo.user_id = mainStore.user_id;
		state.pageInfo.pageIndex = 1;
		state.menberList = [];
		getMemberListBuyCity();
	}
});

// 当前元素
const currentItem = computed<any>(() => state.menberList[state.currentIndex]);

// 绑定推广码红娘关系
const bindMatchmakerRelate = async (): Promise<void> => {
	if (!mainStore.parent_id) return;

	const open_id = mainStore.userInfo.open_id || mainStore.userInfo.openid;
	await bindUserRelate(open_id, mainStore.parent_id);
};

// 获取用户信息
const getUserInfo = async (): Promise<void | string> => {
	const code = getQueryString('code');
	// const code = '091FXxFa1dookE0UajGa1lH0AZ3FXxF1';
	if (!code) {
		return useAuthorize();
	}
	const res = await opendIdByCode(code);
  //state.debug = JSON.stringify(res)
	if (res.errorCode == 0) {
		// 已有用户信息
		const userRes = await memberInfo(res.data.userInfo.id);
		if (userRes.data) {
			mainStore.userInfo = userRes.data;
		} else {
			mainStore.userInfo = res.data.userInfo;
		}
		bindMatchmakerRelate();
    setTimeout(()=>{
      getMemberListBuyCity().catch((err) => console.log(err));
    },1000)
	} else if (res.errorCode == 1) {
		// 获取失败
		return useAuthorize();
	} else {
    setTimeout(async ()=>{
      await getMemberListBuyCity().catch((err) => {

      });
      //state.debug6 = '6666getMemberListBuyCity:'+state.province
      // 添加用户信息
      const { openid, nickname, headimgurl, country, province, sex } = res.data.openid;
      const params = {
        parent_id: mainStore.parent_id || '',
        opendId: openid,
        nickName: nickname,
        avatarUrl: headimgurl,
        gender: sex,
        province: state.province,
        city: state.city,
        country: state.country
      };
      const userRes = await addUser(params);
      //state.debug4 = 'userRes:'+JSON.stringify(userRes)
      mainStore.userInfo = userRes.data;
    },1000)
  }
};

// 定位城市获取列表
const getMemberListBuyCity = (): Promise<void> => {
  //state.debug2 = '正在获取定位城市获取列表'
	state.pageInfo.pageIndex = 1;
	state.menberList = [];
	return new Promise<void>((resolve, reject) => {
		// 获取城市
		wxApiReady(['getLocation'])
			.then((res) => {
				wx.getLocation({
					type: 'wgs84',
					success: async (res: any) => {
            //state.debug3 = 'wx.getLocation：'+JSON.stringify(res)
						const { latitude, longitude } = res;
						const addressRes = await getAddressByGPS(latitude, longitude);
            //state.debug3 += 'addressRes：'+JSON.stringify(addressRes)
						const { city, district, province } = addressRes.data.result.address_component;
						state.city = city;
						state.province = province;
						state.country = district;
						state.pageInfo.city = city;
						state.active = '同城';
						// 设置选择器默认城市
						const city_list: any = areaList.city_list;
						state.areaDefaultCode = Object.keys(city_list).find((key) => {
							return city_list[key] === city;
						});
						await getMemberList();
						resolve();
					},
					complete: (res: any) => {
					}
				});
			})
			.catch((err: Error) => {
				getMemberList();
			});
	});
};

// 性别筛选
const sexMenuChange = (value: DropdownItemOption) => {
	state.pageInfo.pageIndex = 1;
	state.menberList = [];
	getMemberListBuyCity();
};

// 成为vip
const vipPopupRef = ref<InstanceType<typeof vipPopup> | null>(null);
const becomeVip = () => {
	vipPopupRef.value!.showPopup();
};
// 开通vip套餐
const openVipPackage = async (currentPackage: any) => {
	const packageParams = {
		user_id: mainStore.user_id,
		vip_id: currentPackage.id,
		amount: currentPackage.price
	};

	// 创建vip套餐订单
	const res = await createVipOrder(packageParams);
	const oid: number = res.data;
  Toast.loading({
    message: '加载中...',
    forbidClick: true,
  });
	const params: any = await wxVipPay(oid);
	wxApiReady(['chooseWXPay'])
		.then((res) => {
			wx.chooseWXPay({
				timestamp: params.timeStamp, // 支付签名时间戳，注意微信 jssdk 中的所有使用 timestamp 字段均为小写。但最新版的支付后台生成签名使用的 timeStamp 字段名需大写其中的 S 字符
				nonceStr: params.nonceStr, // 支付签名随机串，不长于 32 位
				package: params.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
				signType: params.signType, // 微信支付V3的传入 RSA ,微信支付V2的传入格式与V2统一下单的签名格式保持一致
				paySign: params.paySign, // 支付签名
				success: async (result: object) => {
					// 支付成功后的回调函数
					console.log(result);
					Toast.success('支付成功');
					vipPopupRef.value!.closePopup();
				}
			});
		})
		.catch((err: Error) => console.log(err));
};

// 付费一元
const payOneYuan = async (): Promise<void | ToastOptions> => {
	const like_user_id = currentItem.value.user_id;

	// 单次付费看视频订单
	const res = await createOneYuanOrder(mainStore.user_id, like_user_id);
	if (res.errorCode != 0) return Toast(res.errorInfo);
	const oid: number = res.data;
  Toast.loading({
    message: '加载中...',
    forbidClick: true,
  });
	const params: any = await wxPay(oid);
	wxApiReady(['chooseWXPay'])
		.then((res) => {
			wx.chooseWXPay({
				timestamp: params.timeStamp, // 支付签名时间戳，注意微信 jssdk 中的所有使用 timestamp 字段均为小写。但最新版的支付后台生成签名使用的 timeStamp 字段名需大写其中的 S 字符
				nonceStr: params.nonceStr, // 支付签名随机串，不长于 32 位
				package: params.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
				signType: params.signType, // 微信支付V3的传入 RSA ,微信支付V2的传入格式与V2统一下单的签名格式保持一致
				paySign: params.paySign, // 支付签名
				success: async (result: object) => {
					// 支付成功后的回调函数
					console.log(result);
					state.payShow = false;
					Toast.success('支付成功');
					iframeRefs[currentItem.value.id].play();
					// 添加观看记录
					await saveBrowseRecord(mainStore.user_id, like_user_id);
				}
			});
		})
		.catch((err) => console.log(err));
};

// 视频点击
const videoClick = async (like_user_id: number) => {
	if (!mainStore.userInfo.state || mainStore.userInfo.state == 0) {
		router.push('registered');
		return;
	}
	// 单次付费看视频支付前的检查
	const res = await checkUserStateByOneYuan(mainStore.user_id, like_user_id);
	if (res.errorCode == 0) {
		// 一元付费弹窗
		state.payShow = true;
	} else if (res.errorCode == 1) {
		iframeRefs[currentItem.value.id].play();
	} else {
		Toast(res.errorInfo);
	}
};

// 头像点击
const avatarClick = (user_id: number): void => {
	if (!mainStore.userInfo.state || mainStore.userInfo.state == 0) {
		router.push('registered');
		return;
	}
	router.push({ name: 'userDetail', query: { user_id, type: 'user' } });
};

// 收藏/取消收藏
const collect = async (like_user_id: number, index: number): Promise<void> => {
	if (!mainStore.userInfo.state || mainStore.userInfo.state == 0) {
		router.push('registered');
		return;
	}
	const res = await saveCollect(mainStore.user_id, like_user_id);
	Toast(res.errorInfo);
	const { is_collect, like_num } = state.menberList[index];
	const isCollect: boolean = res.data !== 1 ? false : true;
	state.menberList[index].is_collect = isCollect ? 0 : 1;
	state.menberList[index].like_num = isCollect ? like_num - 1 : like_num + 1;
};

// 分享
const initShare = async () => {
	wxApiReady(['onMenuShareAppMessage', 'onMenuShareTimeline'])
		.then((res) => {
			wx.onMenuShareAppMessage({
				title: '缘分E站', // 分享标题
				desc: currentItem.value.username, // 分享描述
				link: `https://ztcy.huimaibuy.com/h5/#/index?share_user_id=${currentItem.value.user_id}`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致
				imgUrl: currentItem.value.head_img_url, // 分享图标
				type: 'link', // 分享类型,music、video或link，不填默认为link
				dataUrl: '', // 如果 type 是music或video，则要提供数据链接，默认为空
				success: async () => {
					// 用户点击了分享后执行的回调函数
					// 更新转发数量
					const res = await updateShareCount(currentItem.value.user_id);
					console.log(res);
				},
				cancel: (res: any) => {
					console.log(res);
				}
			});
			wx.onMenuShareTimeline({
				title: '缘分E站', // 分享标题
				link: `https://ztcy.huimaibuy.com/h5/#/index?share_user_id=${currentItem.value.user_id}`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致
				imgUrl: currentItem.value.head_img_url, // 分享图标
				success: async () => {
					// 用户点击了分享后执行的回调函数
					// 更新转发数量
					const res = await updateShareCount(currentItem.value.user_id);
					console.log(res);
				},
				cancel: (res: any) => {
					console.log(res);
				}
			});
		})
		.catch((err) => console.log(err));
};

// 拨打电话
const callMobile = (mobile: string): void => {
	if (!mainStore.userInfo.state || mainStore.userInfo.state == 0) {
		router.push('registered');
		return;
	}
	state.mobile = `tel:${mobile}`;
};

// 视频组件dom列表
interface IIframeRefs {
	[key: number | string]: any;
}
let iframeRefs: IIframeRefs = {};
const setItemRef = (el: Element | ComponentPublicInstance | null, key: number | string) => {
	if (el) {
		iframeRefs[key] = el;
	}
};

// swiper 切换
let oldSwiperIndex = ref<number>(0);
let timer: NodeJS.Timeout | null = null;
const onSlideChange = (e: SwiperClass) => {
	if (timer) {
		clearTimeout(timer);
		timer = null;
	}

	// 防抖 切换tab 认证会员弹窗弹出 / initShare()频繁调用问题
	timer = setTimeout(() => {
		if (e.activeIndex >= 3 && state.showFlag && state.active === '认证会员') {
			state.vipShow = true;
			state.showFlag = false;
		}
		// 加载更多
		if (e.activeIndex + 1 == state.menberList.length) {
			getMemberList();
		}
		state.currentIndex = e.activeIndex;

		// 重新加载当前视频
		if (currentItem.value && currentItem.value?.vcr.video_url) {
			nextTick(() => {
				iframeRefs[currentItem.value.id].videoRef.load();
			});
		}

		// 暂停上条视频
		const pvreItem = state.menberList[oldSwiperIndex.value];
		if (pvreItem && pvreItem.vcr.video_url) {
			nextTick(() => {
				iframeRefs[pvreItem.id].videoRef.pause();
			});
		}
		oldSwiperIndex.value = e.activeIndex;

		initShare();
	}, 500);
};

// 选择城市确认
const areaConfirm = (result: AreaColumnOption[]) => {
	state.pageInfo.pageIndex = 1;
	state.menberList = [];
	state.pageInfo.is_vip_video = null;
	state.pageInfo.city = result[1].name;
	getMemberList();
	state.active = '同城';
	state.areaShow = false;
};

// tab切换
const tabsBeforeChange = (name: number | string): boolean => {
	state.pageInfo.pageIndex = 1;
	state.menberList = [];
	if (name === '全部') {
		state.pageInfo.city = '';
		state.pageInfo.is_vip_video = null;
		getMemberList();
	} else if (name === '同城') {
		state.pageInfo.is_vip_video = null;
		getMemberListBuyCity();
	} else {
		state.pageInfo.is_vip_video = 1;
		getMemberList();
	}
	state.currentIndex = 0;
	oldSwiperIndex.value = 0;
	return true;
};

// 获取用户列表
const getMemberList = async () => {
	const res = await memberList(state.pageInfo);
	if (res.data.dataList.length) {
		state.menberList = [...state.menberList, ...res.data.dataList];
		state.pageInfo.pageIndex++;
		initShare();
	}
	console.log(state.menberList);
};
</script>

<style lang="scss" scoped>
:deep(.van-tabs) {
	width: 100%;
	.van-tabs__wrap {
		height: 50px !important;
		.van-tabs__nav {
			justify-content: space-between;
			.van-tab {
				flex: auto;
				padding: 0;
				font-size: 16px;
			}
			.van-tab--active {
				font-size: 17px;
				font-weight: bold;
			}
		}

		.van-tabs__line {
			bottom: 20px;
			background: #f6438a;
		}
	}
}

:deep(.van-dropdown-menu) {
	.van-dropdown-menu__bar {
		box-shadow: none;
		background: white;
		.van-dropdown-menu__title {
			color: #f54386;
			font-size: 13px;
			&::after {
				border-color: transparent transparent #f54386 #f54386;
			}
		}
	}
	.van-popup--top {
		border-radius: 0 0 15px 15px;
	}
}

.home {
	padding: 0 15px;
	.header {
		@include flx-justify-between;
		height: 60px;
		.city {
			@include flx-align-center;
			height: 100%;
			span {
				font-size: 13px;
				margin-left: 2px;
			}
			.play {
				transform: rotate(90deg);
			}
		}
		.tabs {
			@include flx-center;
			height: 100%;
			width: 190px;
		}
	}
}
</style>
